package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.constants.GoodsTypeConstant;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleManTable;
import com.gdk.ksoft.data.entry.tables.SaleTable;
import com.gdk.ksoft.data.entry.tables.ShoppingCartGoodsTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.ui.works.models.FworkGoodsOrderModel;
import com.gdk.ksoft.ui.works.models.FworkOrderInfoModel;
import com.gdk.ksoft.assembly.dialog.BluetoothPrinterDialog;
import com.gdk.ksoft.assembly.utils.TaskUtils;
import com.gdk.ksoft.assembly.utils.extensions.CanvasUtils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.DbModelSelector;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zkc.helper.printer.PrinterClass;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 订单确认页面
 */
public class OrderConfirmationActivity extends Activity {

    @ViewInject(R.id.porderConfirmation_txtTitle)
    private TextView txtTitle;//标题栏
    @ViewInject(R.id.porderConfirmation_txtGoodsCount)
    private TextView txtGoodsCount;//商品统计
    @ViewInject(R.id.porderConfirmation_txtGoodsKinds)
    private TextView txtGoodsKinds;//商品种类统计
    @ViewInject(R.id.porderConfirmation_txtMoney)
    private TextView txtMoney;//商品金额
    @ViewInject(R.id.porderConfirmation_txtDeliverGoodsTime)
    private TextView txttDeliverGoodsTime;//送货时间
    @ViewInject(R.id.porderConfirmation_etNoteInformation)
    private EditText etNotInformation;//备注信息

    private int netCustomerId = 0;//客户网络ID
    private int netAddressId = 0;//客户送货地址网络ID
    private int pieceNum = 0, singleNum = 0, kindsNum = 0;//商品件数，散数，种类数
    private double totalMoney = 0;//总金额数
    private String orderNoForSale = "",orderNoForReturn = "";//销售单号,退货单号
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirmation);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        Intent intent = getIntent();
        if (intent != null) {//获取上个页面传过来的数据
            netCustomerId = intent.getIntExtra("netCustomerId", 0);//获取客户网络ID
            netAddressId = intent.getIntExtra("netAddressId", 0);//获取送货地址网络ID
            pieceNum = intent.getIntExtra("goodsPieceNum", 0);//获取商品件数
            singleNum = intent.getIntExtra("goodsSingleNum", 0);//获取商品散数
            kindsNum = intent.getIntExtra("goodsKindsNum", 0);//获取商品种类数
            totalMoney = intent.getDoubleExtra("goodsTotalMoney", 0);//获取商品总金额
            txtGoodsCount.setText("数量:" + pieceNum + "件" + singleNum + "散");//获取商品数量统计
            txtGoodsKinds.setText("种类:" + kindsNum);//获取商品种类信息
            txtMoney.setText("金额:" + FormatUtils.exactNumber(totalMoney, "0.00"));//获取商品总金额
            txttDeliverGoodsTime.setText(getLocalDate());
            try {
                DbModel customer = dbUtils.findDbModelFirst(DbModelSelector.from(CustomerTable.class)
                                .where("id", "=", netCustomerId));
                txtTitle.setText(customer.getString("mc") + "货单确认");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当天的日期
     * @return
     */
    public String getLocalDate() {
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DAY_OF_MONTH);
        return year + "-" + (month<10?"0"+month:""+month) + "-" + (date<10?"0"+date:""+date);
    }


    /**
     * 控件点击事件
     *
     * @param view
     */
    @OnClick(value = {R.id.porderConfirmation_txtPlaceOrder, R.id.porderConfirmation_txtDeliverGoodsTime,
            R.id.porderConfirmation_txtPrint})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.porderConfirmation_txtPlaceOrder://下单确认
                addGoodsOrder(OrderConfirmationActivity.this);//下单操作
                break;
            case R.id.porderConfirmation_txtDeliverGoodsTime://选择时间
                Calendar calendar = Calendar.getInstance(Locale.CHINA);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int date = calendar.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String month = (monthOfYear+1<10?"0"+(monthOfYear+1):(monthOfYear+1)+"");
                        String day = dayOfMonth<10?"0"+dayOfMonth:""+dayOfMonth;
                        txttDeliverGoodsTime.setText(year + "-" + month + "-" + day);
                    }
                }, year, month, date).show();
                break;
            case R.id.porderConfirmation_txtPrint://打印
                if(MainActivity.pl != null && MainActivity.pl.getState() == PrinterClass.STATE_CONNECTED) {
                    //直接打印
                    printOrders();//打印单据
                }else{
                    new BluetoothPrinterDialog(this, new BluetoothPrinterDialog.OnBluetoothConnectedListener() {
                        @Override
                        public void onBluetoothConnected(boolean isSuccessful) {
                            if(isSuccessful) printOrders();//连接成功，开始打印单据
                        }
                    }).show();
                }
                break;
        }
    }

    /**
     * 添加商品订单
     */
    public void addGoodsOrder(final Context context) {
        new AsyncTask<Void, Void, Void>() {
            private String errorMessage = null;
            private ProgressDialog dialog = null;
            private AsyncTask task = null;//任务对象

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                TaskUtils.sendMessageToBackgroundService(context, false);
                task = this;//获取添加商品订单任务对象
                dialog = ProgressDialog.show(context, "", "正在提交数据...");
                dialog.setCancelable(true);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        try{
                            task.cancel(true);
                            task = null;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        Toast.makeText(context,"您取消了下单任务!",Toast.LENGTH_SHORT).show();
                        TaskUtils.sendMessageToBackgroundService(context,true);
                    }
                });
            }

            @Override
            protected Void doInBackground(Void... params) {
                SQLiteDatabase database = dbUtils.getDatabase();
                try {
                    database.beginTransaction();
                    FworkOrderInfoModel orderInfo = saveSaleGoodsOrder(dbUtils, true);//取销售单数据
                    if (orderInfo != null) saveSaleOrder(dbUtils, orderInfo);
                    orderInfo = saveSaleGoodsOrder(dbUtils, false);//取退货数据
                    if (orderInfo != null) saveSaleOrder(dbUtils, orderInfo);
                    dbUtils.delete(ShoppingCartGoodsTable.class, WhereBuilder.b("kh_id", "=", netCustomerId)//清空购物车商品数据
                            .and("shdz_id", "=", netAddressId));
                    database.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                    errorMessage = "下单失败!原因：" + e.getMessage();
                }finally {
                    database.endTransaction();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if (dialog != null && dialog.isShowing()) dialog.dismiss();
                TaskUtils.sendMessageToBackgroundService(context,true);
                if (errorMessage != null) {
                    Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "下单完成！", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(context, MainActivity.class));
                    ((Activity)context).finish();
                }
            }
        }.execute();
    }

    /**
     * 保存一个销售单,返回一个销售单号
     *
     * @param dbUtils
     * @return
     */
    public void saveSaleOrder(DbUtils dbUtils, FworkOrderInfoModel orderInfo) throws Exception {
        if (orderInfo == null) return;
        SaleTable saleTable = new SaleTable();
        saleTable.ddlx = 1;//此处是订单
        saleTable.djbz = 0;//0表示单机
        saleTable.djh = orderInfo.orderNo;
        saleTable.fhsj = FormatUtils.standardDatetime(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
        saleTable.js = orderInfo.pieceNum;
        saleTable.ss = orderInfo.singleNum;
        saleTable.jsfs = 0;//此处暂时为0
        saleTable.kh_id = netCustomerId;
        saleTable.shdz_id = netAddressId;
        saleTable.pssm = etNotInformation.getText().toString();
        saleTable.sfje = orderInfo.totalMoney;
        saleTable.zqts = 0;//暂时为0
        saleTable.xdsj = FormatUtils.standardDatetime(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
        dbUtils.save(saleTable);//保存订单数据
    }

    /**
     * 储存销售单商品数据
     *
     * @param dbUtils
     * @throws Exception
     */
    public FworkOrderInfoModel saveSaleGoodsOrder(DbUtils dbUtils, boolean isBigThanZero) throws Exception {
        FworkOrderInfoModel orderInfo = null;
        Selector selector = Selector.from(ShoppingCartGoodsTable.class)
                .where("kh_id", "=", netCustomerId).and("shdz_id", "=", netAddressId)
                .and("hsdwsl", isBigThanZero ? ">" : "<", 0);
        List<ShoppingCartGoodsTable> goodslst = dbUtils.findAll(selector);
        if (goodslst == null || goodslst.size() == 0) return null;
        String goodsNo = isBigThanZero?(TextUtils.isEmpty(orderNoForSale)?"NOB"+System.currentTimeMillis():orderNoForSale)
                :(TextUtils.isEmpty(orderNoForReturn)?"NOS"+System.currentTimeMillis():orderNoForReturn);
        orderInfo = new FworkOrderInfoModel();
        orderInfo.orderNo = goodsNo;
        for (ShoppingCartGoodsTable item : goodslst) {
            orderInfo.totalMoney += item.yfje;//统计金额
            orderInfo.singleNum += item.xsdwss;//统计销售单位散数
            orderInfo.pieceNum += item.xsdwsl;//统计销售单位数量
        }
        for (ShoppingCartGoodsTable item : goodslst) {
            SaleGoodsTable goodsVal = new SaleGoodsTable();
            goodsVal.bz = item.bz;
            goodsVal.bzlsj = item.bzlsj;
            goodsVal.bzq = item.bzq;
            goodsVal.bzxsdwj = item.bzxsdwj;
            goodsVal.csrq = item.zdsj;
            goodsVal.gg = item.gg;
            goodsVal.hsdw = item.hsdw;
            goodsVal.hsdwsl = item.hsdwsl;
            goodsVal.hsgx = item.hsgx;
            goodsVal.kh_id = item.kh_id;
            goodsVal.khdz_id = item.shdz_id;
            goodsVal.lx = item.lx;
            goodsVal.mc = item.mc;
            goodsVal.sp_id = item.sp_id;
            goodsVal.tm = item.tm;
            goodsVal.xsd_id = goodsNo;
            goodsVal.xsdw = item.xsdw;
            goodsVal.xsdwsl = item.xsdwsl;
            goodsVal.xsdwss = item.xsdwss;
            goodsVal.xsyj = item.xsyj;
            goodsVal.yfje = item.yfje;
            goodsVal.zdsj = item.zdsj;
            dbUtils.save(goodsVal);
        }
        return orderInfo;
    }

    /**
     * 请求商品的订单号
     * @param isNormalOrder true - 订单   false - 退单
     * @return
     * @throws Exception
     */
    public String requestOrderNo(boolean isNormalOrder)throws Exception {
        try {
            if (!NetworkUtils.isNetAvailable(OrderConfirmationActivity.this))
                return null;//如果网络不可用
            String methodName = isNormalOrder ? "Cx_XsdDjh" : "Cx_XstDjh";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
            System.out.println("-----> 请求单据号数据数据是：" + messageBody);
            RequestParams params = new RequestParams();
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            String result = FileUtils.stream2string(new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                    .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params), "UTF-8");
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    return resultModel.Data;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //生成一个临时订单号，NOB-订货单，NOS-订货退单
        return "NO" + (isNormalOrder ? "B" : "S") + System.currentTimeMillis();
    }

    /**
     * 打印单据
     */
    public void printOrders() {
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(OrderConfirmationActivity.this, "", "正在打印...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    printOrderList(true);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorMessage = "打印失败!原因："+e.getMessage();
                }
                try {
                    printOrderList(false);
                } catch (Exception e) {
                    e.printStackTrace();
                    errorMessage = "打印失败!原因："+e.getMessage();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                Toast.makeText(OrderConfirmationActivity.this,
                        errorMessage!=null?errorMessage:"打印成功!",Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    /**
     * 打印单子
     * @param isNormalOrder true - 订单   false - 退单
     * @throws Exception
     */
    public void printOrderList(final boolean isNormalOrder)throws Exception{
        if(isNormalOrder) orderNoForSale = requestOrderNo(true);//请求订单
        else orderNoForReturn = requestOrderNo(false);//请求退单
        List<FworkGoodsOrderModel> orderModelList = FworkDbHelper.findAllOrderlst(dbUtils,netCustomerId, netAddressId,isNormalOrder?1:0);
        if(orderModelList == null || orderModelList.size()<=0) return;//不满足打印条件，不打印
        DbModel dbSaleMan = dbUtils.findDbModelFirst(DbModelSelector.from(SaleManTable.class).select("gsmc", "RealName"));
        DbModel dbCustomer = dbUtils.findDbModelFirst(DbModelSelector.from(CustomerTable.class).where("id", "=", netCustomerId).select("mc"));
        DbModel dbAddress = dbUtils.findDbModelFirst(DbModelSelector.from(DeliverGoodsTable.class).where("id", "=", netAddressId).select("shdz"));
        String companyName = dbSaleMan.getString("gsmc");
        final int WIDTH = 840,MARGIN = 5;//纸张宽度和纸张边距
        Bitmap bitmap = Bitmap.createBitmap(WIDTH, 480 + 140 * orderModelList.size(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        float currentHeight = 0;//纸张当前高度
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);//设置文字居中
        paint.setTextSize(45f);
        currentHeight = CanvasUtils.drawText(canvas,paint,companyName+(isNormalOrder?"订货清单":"退货清单"),WIDTH/2,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas, paint, 5, currentHeight, WIDTH - 10, 4);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setTextSize(38f);
        currentHeight = CanvasUtils.drawText(canvas,paint,"客户："+dbCustomer.getString("mc"),MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"地址："+dbAddress.getString("shdz"),MARGIN,currentHeight,-1);
        String orderNo = isNormalOrder?orderNoForSale:orderNoForReturn;//获取单号
        if(!orderNo.startsWith("NO"))//如果是网络单号才打印
            currentHeight = CanvasUtils.drawText(canvas,paint,"单号："+orderNo,MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        final String[] columns = {"规格","发价","数量","金额"};
        for(int i=0;i<columns.length;i++){
            float py = CanvasUtils.drawText(canvas,paint,columns[i],MARGIN + i*(WIDTH-10)/columns.length,currentHeight,-1);
            if(i == columns.length-1) currentHeight = py;
        }
        paint.setTextSize(35f);
        for(FworkGoodsOrderModel item : orderModelList){//绘制商品列
            String goodsTm = (item.goodsType == 0?"":"("+GoodsTypeConstant.getGoodsType().get(item.goodsType)+")")
                    +item.goodsInfo.tm;
            currentHeight = CanvasUtils.drawText(canvas,paint,goodsTm+"  "+item.goodsInfo.mc,0,currentHeight,WIDTH);
            CanvasUtils.drawText(canvas,paint,item.goodsInfo.gg,0,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint, "￥"+FormatUtils.exactNumber(item.finalPrice/item.goodsModuleInfo.hsgx,"0.00"),WIDTH/4,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint,(item.pieceNum==0?"":item.pieceNum+item.goodsModuleInfo.jldwmc)+(item.singleNum==0?"":item.singleNum+item.goodsInfo.dw),2*WIDTH/4,currentHeight,WIDTH/4);
            currentHeight = CanvasUtils.drawText(canvas,paint,"￥"+FormatUtils.exactNumber(item.totalMoney,"0.00"),3*WIDTH/4,currentHeight,WIDTH/4);
            currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        }
        paint.setTextSize(38f);
        HashMap<String,Object> totalInfo = FworkDbHelper.getOrderTotalInfo(dbUtils,netAddressId,netCustomerId,isNormalOrder?1:0);
        if(totalInfo!=null) {//获取商品统计信息
            CanvasUtils.drawText(canvas, paint, totalInfo.get("totalPieceNum")+"件"+totalInfo.get("totalSingleNum")+"散", 0, currentHeight, WIDTH / 3);
            CanvasUtils.drawText(canvas, paint, totalInfo.get("totalKinds")+"种", WIDTH / 3, currentHeight, WIDTH / 3);
            currentHeight = CanvasUtils.drawText(canvas, paint, "￥"+FormatUtils.exactNumber(totalInfo.get("totalMoney"),"0.00"), 2 * WIDTH / 3, currentHeight, WIDTH / 3);
        }
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        CanvasUtils.drawText(canvas,paint,"开票人:"+dbSaleMan.getString("RealName"),0,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"打印时间:"+FormatUtils.standardDatetime(new java.util.Date(),"yyyy/MM/dd HH:mm:ss"),
                WIDTH/3,currentHeight,-1);
        CanvasUtils.drawText(canvas,paint,"购货检验人(签字):",0,currentHeight,-1);
//        FileUtils.writeImageToFile(bitmap, Bitmap.CompressFormat.JPEG,100,"/sdcard/1.jpg");
        MainActivity.pl.printImage(bitmap);
    }


    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.porderConfirmation_txtBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
